package com.fengmi.filter.security;

import cn.hutool.json.JSONUtil;
import com.fengmi.entity.SysUser;
import com.fengmi.utils.security.JwtUtils;
import com.fengmi.utils.security.RsaUtils;
import com.fengmi.vo.InfoResult;
import io.jsonwebtoken.JwtException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;

/**
 * Author: 施俊豪
 * Date: 2022/2/6 0:27
 * Note: 自定义security过滤器
 * 获取令牌
 * 解析令牌
 * 将用户信息放入spring security的context中
 *
 * 该过滤器拦截所有请求(/**)
 */
public class MyBasicAuthenticationFilter extends BasicAuthenticationFilter {

    public MyBasicAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        // 放行登录请求
        String requestURI = request.getRequestURI();

        if("/user/login".equals(requestURI)){
            // 放行
            chain.doFilter(request,response);

            // 如果是登录，就不走下面代码
            return;
        }

        if("/user/verify".equals(requestURI)){
            // 放行
            chain.doFilter(request,response);

            // 如果是登录，就不走下面代码
            return;
        }

        // 从请求头中获取jwt令牌
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            // 直接拦截,并给客户端响应
            response(response,new InfoResult(false,"令牌不能为空!!!",""));

            return;
        }

        // 解析令牌
        try {
            // 获取公钥
            PublicKey publicKey = RsaUtils.getPublicKey(ResourceUtils.getFile("classpath:rsa.pub").getPath());

            // 从用户在拿取令牌
            SysUser infoFromToken = (SysUser) JwtUtils.getInfoFromToken(token, publicKey, SysUser.class);

            // 封装用户的角色和权限信息
            String roles = infoFromToken.getRoles();
            String permissions = infoFromToken.getPermissions();

            // 利用springsecurity工具类提供的方法
            List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(roles + permissions);

            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(infoFromToken, null,
                    /*用户的角色和权限信息*/authorities);
            // 将用户信息放入springsecurity上下文中
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);

            // 放行
            chain.doFilter(request,response);
            } catch (Exception e) {
            e.printStackTrace();
            if(e instanceof JwtException){
                response(response,new InfoResult(false,"令牌不合法!!!",""));
            }else{
                response(response,new InfoResult(false,"其他异常!!!",""));
            }

        }
    }

    private void  response(HttpServletResponse response, InfoResult res){
        try {
            response.setContentType("application/json;charset=utf-8");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//SC_UNAUTHORIZED: 401  没有认证
            PrintWriter out = response.getWriter();

            out.write(JSONUtil.toJsonPrettyStr(res));
            out.flush();
            out.close();
        }catch (Exception e){

        }

    }
}
